<template>
  <div>
    <div class="header-wrapper">
      <h3>默认审批流程管理</h3>
      <div>
        <Button @click="handleBackClick" style="margin: 0 10px 0 60px;">返回</Button>
        <Button @click="handleSaveClick" type="success">保存</Button>
      </div>
    </div>
    <div class="container-wrapper">
      <div class="process-info-wrapper">
        <div class="paragraph-title">流程基本信息</div>
        <Form
          :label-width="80"
          :model="processForm"
          :rules="processFormRules"
          class="process-form"
          ref="processForm"

        >
          <FormItem label="流程编号" prop="flownum">
            <Input placeholder="请输入流程编号" v-model="processForm.flownum"></Input>
          </FormItem>
          <FormItem label="流程种类" prop="remake">
            <Select
              @on-change="handleRemakeChange"
              label-in-value
              placeholder="请选择流程种类"
              v-model="processForm.remake"
            >
              <Option
                :key="item.code"
                :value="item.code"
                v-for="item in processNameList"
              >{{ item.dictdesc }}</Option>
            </Select>
          </FormItem>
          <FormItem label="审批内容" prop="treename">
            <Input
              @click.native="handleSelectWorkClick"
              placeholder="请选择审批内容"
              v-model="processForm.treename"
            >
              <Icon slot="suffix" type="md-add" />
            </Input>
          </FormItem>
          <FormItem label="启用状态" prop="status">
            <i-switch :false-value="'2'" :true-value="'1'" v-model="processForm.status">
              <span slot="open">开</span>
              <span slot="close">关</span>
            </i-switch>
          </FormItem>
        </Form>
      </div>

      <div class="default-process-wrapper">
        <div class="paragraph-title">默认审批流程</div>
        <div class="process-box">
          <div class="process-first">
            <div class="circle-wrapper">
              <p>发起申请</p>
              <div class="circle-box">{{ firstProcessNode.tenantid }}</div>
            </div>
            <div class="add-button-wrapper">
              <Icon @click="handleFirstAddClick" class="add-button" type="ios-add" v-if="isEdit" />
              <Icon @click="handleFirstAddClickNew" class="add-button" type="ios-add" v-else />
            </div>
          </div>

          <div class="process-card-list">
            <ProcessNodeCard
              :isEdit="isEdit"
              :key="index"
              :node="item"
              @on-add-click="handleCardAddClick(item,index)"
              @on-add-click-new="handleCardAddClickNew(index)"
              @on-del-click="handleCardDelClick(item)"
              @on-del-click-new="handleCardDelClickNew(index)"
              @on-edit-click="handleCardEditClick(item)"
              @on-edit-click-new="handleCardEditClickNew(item,index)"
              v-for="(item, index) in approveList"
            />
          </div>
        </div>
      </div>
    </div>

    <Modal
      @on-cancel="handleProcessModalCancel"
      class="process-modal"
      title="默认审批设置"
      v-model="processModalVisiable"
    >
      <Form :label-width="90" :model="nodeAddForm" :rules="nodeAddFormRules" ref="nodeAddForm">
        <FormItem label="审批名称" prop="approvalName">
          <Select placeholder="请选择审批名称" v-model="nodeAddForm.approvalName">
            <Option
              :key="item.code"
              :value="item.code"
              v-for="item in approvalNameList"
            >{{ item.dictdesc }}</Option>
          </Select>
        </FormItem>
        <FormItem label="审批人员" prop="approver">
          <Input
            @click.native="handleSelectPeopleClick"
            placeholder="请选择人员"
            v-model="nodeAddForm.approver"
          >
            <Icon slot="suffix" type="md-add" />
          </Input>
        </FormItem>
        <FormItem label="审批人员公司" prop="approvalCompany">
          <Input disabled placeholder="请输入流程编号" v-model="nodeAddForm.approvalCompany"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleProcessModalCancel">重置</Button>
        <Button @click="handleFlowNodeEidtOk" type="primary" v-if="isFlowNodeEdit">提交</Button>
        <Button @click="handleProcessModalOk" type="primary" v-else>提交</Button>
      </div>
    </Modal>

    <!-- 选择审批人弹窗 -->
    <ModalProcesser @on-select-success="handleTableSelect" v-model="selectProcesserModalVisiable" />
    <!-- 选择工序弹窗 -->
    <ModalWrokList
      :workIds="workIds"
      :flowType="processForm.remakeText"
      @on-select-success="handleWorksSelect"
      v-model="selectWorkModalVisiable"
    />
  </div>
</template>

<script>
import {
  getFlowType,
  getFlowInfo,
  addFlowNode,
  delFlowNode,
  initProcessFlow,
  unpdateFlowNode,
  processEditSave,
  getWorkNamefromIds
} from '@/api/message.js';
import ModalProcesser from './modal-processer';
import ModalWrokList from './modal-worklist';
import ProcessNodeCard from './process-node-card';

export default {
  components: {
    ModalProcesser,
    ModalWrokList,
    ProcessNodeCard
  },
  data () {
    return {
      isEdit: false,
      flowId: '',
      currentType: 0, // 当前选择的流程种类value
      processForm: {
        flownum: '',
        status: 2, // 1开启 2关闭
        remake: '', // 流程种类
        treename: '', // 审查内容
        remakeText: '' // 流程种类
      },
      workIds: '', // id字符串 '21322, 21323'  String
      processNameList: [], // 流程种类list

      processFormRules: {
        flownum: [
          { required: true, message: '请输入流程编号', trigger: 'blur' }
        ],
        treename: [{ required: true, message: '请选择审批内容' }],
        remake: [{ required: true, message: '请选择流程种类' }],
        status: [{ required: true }]
      },

      approveList: [], // 流程列表
      firstProcessNode: {}, // 编辑时候流程第一个

      // 审批节点弹窗
      isFlowNodeEdit: false,
      oprFlowNode: {},
      curIndex: 0,
      nextIndex: null,
      processModalVisiable: false,
      nodeAddForm: {
        approvalName: '', // 被选中审批名称的id
        approver: '', // 审批人员
        approvalCompany: '', // 审批人员所在公司
        deptName: '',
        phone: '',
        approverId: '' // 审批人id
      },
      nodeAddFormRules: {
        approvalName: [{ required: true, message: '请选择审批流程' }],
        approver: [{ required: true, message: '请选择审批人员' }]
      },
      approvalNameList: [], // 审批名称list

      selectProcesserModalVisiable: false,

      selectWorkModalVisiable: false
    };
  },
  created () {
    if (this.$route.query.id) {
      this.isEdit = true;
      this.flowId = this.$route.query.id;
    }
  },
  mounted () {
    if (this.isEdit) {
      this.getFlowInfo();
    }
    this.getProcessNameList();
  },
  methods: {
    async getFlowInfo () {
      const resp = await getFlowInfo(this.flowId);
      console.log('默认流程详情 res=>', resp);
      const info = resp.data.data;
      this.approveList = (info.nodeList || []).map(item => {
        item.remake = item.dwName;
        item.tenantid = item.curuserName;
        return item;
      });

      // 第一个是发起流程，切出来
      this.firstProcessNode = this.approveList.shift();

      this.processForm.flownum = info.flownum;
      this.processForm.status = String(info.status);
      // info.treename  流程种类id
      this.processForm.remake = Number(info.treename);
      console.log(this.processForm.remake, '流程种类id?');
      this.currentType = this.processForm.remake;
      this.getApprovalNameList();
      this.processForm.remakeText = info.remake;

      this.workIds = info.presetviceVoList.map(item => item.dataid).join(',');

      // 根据ids查询对应的名字
      const idsarr = this.workIds.split(',');
      const namesResp = await getWorkNamefromIds({ ids: idsarr });
      this.processForm.treename = namesResp.data.data;
    },
    handleBackClick () {
      this.$router.go(-1);
    },
    // 审批名称列表
    async getApprovalNameList () {
      // const type = this.getRelationType(this.currentType);
      try {
        const resp = await getFlowType(this.currentType);
        this.approvalNameList = resp.data.data || [];
      } catch (error) {
        console.error(error);
      }
    },
    // 流程名称列表
    async getProcessNameList () {
      try {
        const resp = await getFlowType(2);
        this.processNameList = resp.data.data || [];
        console.log(this.processNameList);
      } catch (error) {
        console.error(error);
      }
    },
    handleSelectPeopleClick () {
      this.selectProcesserModalVisiable = true;
    },
    handleSelectWorkClick () {
      this.selectWorkModalVisiable = true;
    },
    // 选择人员后回调函数
    handleTableSelect (select) {
      this.nodeAddForm.approver = select.userName;
      this.nodeAddForm.approverId = select.userId;
      this.nodeAddForm.approvalCompany = select.dwName;
      this.nodeAddForm.phone = select.phone;
      this.nodeAddForm.deptName = select.deptName;
    },
    // 选择工序，审批内容确定后
    handleWorksSelect (worknames, ids) {
      this.processForm.treename = worknames;
      this.workIds = ids.join(',');
    },
    handleProcessModalCancel () {
      this.oprFlowNode = {};
      this.curIndex = 0;
      this.isFlowNodeEdit = false;
      this.$refs.nodeAddForm.resetFields();
    },
    handleProcessModalOk () {
      this.$refs.nodeAddForm.validate(async valid => {
        if (valid) {
          /**
           * 增加节点的时候新增和编辑分开处理
           * 编辑提交到后台
           * 新增本地处理
           */
          if (this.isEdit) {
            const data = {
              preNodeId: this.oprFlowNode.nodeid,
              approverId: this.nodeAddForm.approverId,
              nodeName: this.nodeAddForm.approvalName,
              dwmc: this.nodeAddForm.approvalCompany,
              sprxm: this.nodeAddForm.approver,
              phone: this.nodeAddForm.phone
            };
            // deptName: this.nodeAddForm.deptName

            /**
             * this.curIndex < 0,  preNode是firstProcessNode nextNode是approveList第一个
             * 0 < this.curIndex < approveList.lengt-1
             * this.curIndex === approveList.lengt-1  nextNode是nodeId是'END'
             */
            if (
              this.curIndex < this.approveList.length - 1 &&
              this.curIndex > 0
            ) {
              const nextNode = this.approveList[this.curIndex + 1] || {};
              data.nextNodeId = nextNode.nodeid;
            } else if (this.curIndex === this.approveList.length - 1) {
              data.nextNodeId = 'END';
            } else {
              data.nextNodeId = this.approveList[0].nodeid;
            }

            // console.log('增加审批流程节点 req=>', data);
            await addFlowNode(data);
            // console.log('增加审批流程节点 res=>', resp);

            this.processModalVisiable = false;
            this.getFlowInfo();
            this.handleProcessModalCancel();
          } else {
            const data = {
              nodeName: this.nodeAddForm.approvalName,
              remake: this.nodeAddForm.approvalCompany,
              tenantid: this.nodeAddForm.approver,
              curuser: this.nodeAddForm.approverId,
              phone: this.nodeAddForm.phone
            };
            // deptName: this.nodeAddForm.deptName

            this.approvalNameList.forEach(item => {
              if (item.code == data.nodeName) {
                data.nodename = item.dictdesc;
              }
            });

            this.approveList.splice(this.curIndex + 1, 0, data);
            this.processModalVisiable = false;
            this.handleProcessModalCancel();
          }
        }
      });
    },
    handleFlowNodeEidtOk () {
      this.$refs.nodeAddForm.validate(async valid => {
        if (valid) {
          /**
           * 增加节点的时候新增和编辑分开处理
           * 编辑提交到后台
           * 新增本地处理
           */
          if (this.isEdit) {
            const data = {
              nodeid: this.oprFlowNode.nodeid,
              approverId: this.nodeAddForm.approverId,
              dwmc: this.nodeAddForm.approvalCompany,
              sprxm: this.nodeAddForm.approver,
              nodenameId: this.nodeAddForm.approvalName
            };

            // console.log('修改节点 data=>', data);
            await unpdateFlowNode(data);
            this.processModalVisiable = false;
            this.getFlowInfo();
            this.handleProcessModalCancel();
          } else {
            const data = {
              nodeName: this.nodeAddForm.approvalName,
              remake: this.nodeAddForm.approvalCompany,
              tenantid: this.nodeAddForm.approver,
              curuser: this.nodeAddForm.approverId,
              phone: this.nodeAddForm.phone
            };

            this.approvalNameList.forEach(item => {
              if (item.code == data.nodeName) {
                data.nodename = item.dictdesc;
              }
            });

            this.approveList.splice(this.curIndex, 1, data);
            this.processModalVisiable = false;
            this.handleProcessModalCancel();
          }
        }
      });
    },
    // 编辑时候节点处理
    handleFirstAddClick () {
      this.oprFlowNode = this.firstProcessNode;
      this.curIndex = -1;
      this.processModalVisiable = true;
    },
    handleCardEditClick (node) {
      console.log('编辑的节点 ', node);
      this.isFlowNodeEdit = true;
      this.oprFlowNode = node;
      this.nodeAddForm.approvalName = Number(node.nodenameId);
      this.nodeAddForm.approver = node.tenantid;
      this.nodeAddForm.approvalCompany = node.remake;
      this.nodeAddForm.approverId = node.curuser;

      this.processModalVisiable = true;
    },
    handleCardDelClick (item) {
      this.$Modal.confirm({
        title: '确认删除？',
        content: '<p>数据删除后不可恢复，请确认是否删除数据？</p>',
        loading: true,
        onOk: async () => {
          const nodeid = item.nodeid;
          // console.log('删除节点 req=>', nodeid);
          await delFlowNode(nodeid);
          // console.log('删除节点 res=>', resp);
          this.getFlowInfo();
          this.$Modal.remove();
        }
      });
    },
    handleCardAddClick (item, index) {
      // console.log('增加前的节点', item);
      this.oprFlowNode = item;
      this.curIndex = index;

      this.processModalVisiable = true;
    },
    // 新增时候节点处理
    handleFirstAddClickNew () {
      this.curIndex = -1;
      this.processModalVisiable = true;
    },
    handleCardEditClickNew (item, index) {
      this.isFlowNodeEdit = true;
      this.oprFlowNode = item;
      this.curIndex = index;

      this.nodeAddForm.approvalName = item.nodeName;
      this.nodeAddForm.approver = item.tenantid;
      this.nodeAddForm.approvalCompany = item.remake;
      this.nodeAddForm.approverId = item.curuser;
      this.processModalVisiable = true;
    },
    handleCardDelClickNew (index) {
      this.approveList.splice(index, 1);
    },
    handleCardAddClickNew (index) {
      this.curIndex = index;
      this.processModalVisiable = true;
    },
    handleSaveClick () {
      this.$refs.processForm.validate(async valid => {
        if (valid) {
          if (this.isEdit) {
            const Presetflow = JSON.parse(JSON.stringify(this.processForm));
            const remakeIdCopy = Presetflow.remake;
            Presetflow.status = String(Presetflow.status);
            Presetflow.remake = Presetflow.remakeText;
            Presetflow.treename = String(remakeIdCopy);
            const dataIds = this.workIds;
            Presetflow.id = this.flowId;
            const data = {
              Presetflow,
              dataIds
            };
            // console.log('编辑保存 data=>', data);
            await processEditSave(data);
            this.$Message.success('保存成功');
            setTimeout(() => {
              this.$router.go(-1);
            }, 1500);
          } else {
            const Presetflow = JSON.parse(JSON.stringify(this.processForm));
            const remakeIdCopy = Presetflow.remake;
            Presetflow.status = String(Presetflow.status);
            Presetflow.remake = Presetflow.remakeText;
            Presetflow.treename = String(remakeIdCopy);

            const Flownode = this.approveList;
            /**
             * 后台字段变更
             */
            Flownode.forEach(item => {
              item.nodename = item.nodeName;
            });

            const dataIds = this.workIds;
            // delete Presetflow.treename;

            const data = {
              Presetflow,
              Flownode,
              dataIds
            };

            // console.log('新增默认流程保存 data=>', data);
            await initProcessFlow(data);
            this.$Message.success('保存成功');
            setTimeout(() => {
              this.$router.go(-1);
            }, 1500);
          }
        }
      });
    },
    handleRemakeChange (obj) {
      this.processForm.remakeText = obj.label;
      console.log(obj, '选的啥?');
      this.currentType = obj.value;
      this.getApprovalNameList();
    },
    getRelationType (value) {
      const map = [3, 7, 8, 9, 10];
      return map[value - 1];
    }
  }
};
</script>

<style lang="less" scoped>
.header-wrapper {
  display: flex;
  justify-content: space-between;
}
.paragraph-title {
  line-height: 40px;
  background: rgb(247, 243, 243);
  padding-left: 15px;
  box-sizing: border-box;
  margin-top: 20px;
}
.process-form {
  width: 50%;
  margin: 20px 0 0 30px;
  min-width: 400px;
}
.process-box {
  display: flex;
  width: 90%;
  margin: 20px auto 0;
  .process-first {
    margin: 0 20px 20px 0;
    display: flex;
    height: 125px;
    .circle-wrapper {
      width: 50px;
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;
      margin-right: 10px;
      > p {
        margin-bottom: 10px;
      }
      .circle-box {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: green;
        margin-bottom: 25px;

        text-align: center;
        line-height: 40px;
        color: #fff;
      }
    }
    .add-button-wrapper {
      display: flex;
      align-items: center;
      .add-button {
        font-size: 30px;
        background-color: #5a6fce;
        border-radius: 50%;
        color: #fff;
        cursor: pointer;
      }
    }
  }

  .process-card-list {
    display: flex;
    flex-wrap: wrap;
  }
}

.process-modal {
  /deep/ .ivu-modal-body {
    padding: 16px 80px 16px 30px;
  }
}
</style>
